import React, { useState, useEffect, useRef, useMemo } from 'react'
import { useParams, Link, useNavigate } from 'react-router-dom'
// 不再导入chatAPI
import chatAPI from '../api/chat'
import { visitorAPI, request } from '../api/request'
import aiChatData from '../data/AIchat.json'

// vconsole 
// import VConsole from 'vconsole'
// const vConsole = new VConsole()
// window.vConsole = vConsole


// 添加用于预加载图像的实用程序功能
const preloadImage = (src: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    img.onload = () => resolve();
    img.onerror = () => reject();
  });
};

// Create an image cache to avoid reloading the same avatars
const imageCache = new Map<string, boolean>();

// Add DNS prefetching component for faster image loading
const DNSPrefetch: React.FC = () => {
  return (
    <>
      <link rel="dns-prefetch" href="https://knowyou.tos-cn-guangzhou.volces.com" />
      <link rel="preconnect" href="https://knowyou.tos-cn-guangzhou.volces.com" crossOrigin="anonymous" />
      <link rel="dns-prefetch" href="https://images.unsplash.com" />
      <link rel="preconnect" href="https://images.unsplash.com" crossOrigin="anonymous" />
    </>
  );
};


// 预加载aiAvatarUrl以避免多次获取 - 优化预加载逻辑
const PreloadAvatar: React.FC<{ src: string }> = React.memo(({ src }) => {
  // 使用ref避免触发重渲染
  const hasTriggeredRef = useRef(false);

  useEffect(() => {
    if (src && !imageCache.has(src) && !hasTriggeredRef.current) {
      hasTriggeredRef.current = true;
      const img = new Image();
      img.src = src;
      img.onload = () => {
        imageCache.set(src, true);
      };
    }
  }, [src]);

  return null;
}, (prevProps, nextProps) => prevProps.src === nextProps.src);

interface Message {
  id: string
  content: string
  sender: 'user' | 'ai'
  timestamp: Date
  emotionAnalysis?: Record<string, number>
  isAudio?: boolean
}

// 添加类型声明
declare global {
  interface Window {
    SpeechRecognition?: typeof SpeechRecognition;
    webkitSpeechRecognition?: typeof SpeechRecognition;
  }
}

const AIChat: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [messages, setMessages] = useState<Message[]>([])
  const [inputMessage, setInputMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const [sessionId, setSessionId] = useState<string>('')
  const [currentResponse, setCurrentResponse] = useState('')
  const [showActions, setShowActions] = useState(false)
  const [showConfirmDialog, setShowConfirmDialog] = useState(false)
  const [generateVoice, setGenerateVoice] = useState(false)
  const [audioStatus, setAudioStatus] = useState<'idle' | 'loading' | 'playing'>('idle')
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const [lastAudioUrl, setLastAudioUrl] = useState<string | null>(null)
  const [currentAudio, setCurrentAudio] = useState<HTMLAudioElement | null>(null)
  const [audioResponseData, setAudioResponseData] = useState<any>(null)
  const [textResponseData, _setTextResponseData] = useState<any>(null)
  const messagesRef = useRef<Message[]>([])
  const [playingMessageId, setPlayingMessageId] = useState<string | null>(null)
  const [audioDurations, setAudioDurations] = useState<Record<string, number>>({})
  const [_audioProgress, setAudioProgress] = useState<number>(0)
  const animationRef = useRef<number>(0)
  const waveformPatternsRef = useRef<Record<string, number[]>>({})
  const [backgroundImage, setBackgroundImage] = useState<string | null>(null)
  const [backgroundLoaded, setBackgroundLoaded] = useState<boolean>(false)
  const [preloadedImages, setPreloadedImages] = useState<Record<string, boolean>>({})
  // 添加已播放消息追踪
  const autoPlayedMessagesRef = useRef<Set<string>>(new Set());
  // 添加初始加载标志
  const [initialLoadComplete, setInitialLoadComplete] = useState<boolean>(false);
  // 添加avatar加载状态
  const [avatarLoaded, setAvatarLoaded] = useState<boolean>(false);
  // 头像 
  const [aiAvatar, setAiAvatar] = useState('')

  // API基础URL
  // const API_BASE_URL = import.meta.env.VITE_API_BASE_URL; 
  const API_BASE_URL = 'https://python.knomi.me';

  // 从JSON数据中获取AI数据
  const [aiData, setAiData] = useState({
    name: 'Sophia AI',
    avatar: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Z2lybHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=800&q=60',
  })

  // Memoize avatar URL to prevent unnecessary re-renders
  const aiAvatarUrl = useMemo(() => aiData.avatar, [aiData.avatar]);

  // 预渲染头像组件一次，永远使用这个实例
  const [aiAvatarComponent, setAiAvatarComponent] = useState<React.ReactElement | null>(null);

  // 立即加载当前AI的头像和背景
  useEffect(() => {
    if (id) {
      // 找到当前AI数据
      const currentAI = aiChatData.find(item => item.id === id);
      if (!currentAI) return;
      // 1. 立即设置AI数据（不等待图片加载）
      setAiData({
        name: currentAI.username,
        avatar: currentAI.avatar
      });

      // 2. 加载头像（但不阻塞UI渲染）
      if (currentAI.image) {
        const avatarImg = new Image();
        avatarImg.src = currentAI.avatar;
        console.log('头像加载完成', avatarImg.src);

        avatarImg.onload = () => {
          setAvatarLoaded(true);
        };
      }

      // 3. 确定背景图URL
      const savedBgImage = localStorage.getItem(`bg_image_${id}`);
      let bgImageUrl = null;

      if (savedBgImage) {
        console.log('使用本地保存的自定义背景图');
        bgImageUrl = savedBgImage;
      } else if (currentAI.images && currentAI.images.length > 0) {
        bgImageUrl = currentAI.images[0];
      }

      // 4. 立即设置背景图（即使尚未加载完成）
      if (bgImageUrl) {
        console.log('开始加载背景图:', bgImageUrl);
        setBackgroundImage(bgImageUrl);

        // 在背景中加载图片
        const bgImg = new Image();
        bgImg.src = bgImageUrl;
        bgImg.onload = () => {
          console.log('背景图加载完成');
          setBackgroundLoaded(true);
        };
      }
    }
  }, [id]);

  // 在背景加载其他非关键图片资源
  useEffect(() => {
    if (!id) return;

    console.log('开始后台加载其他非关键图片');

    // 此时UI已经可以显示，可以在后台预加载其他图片
    const preloadOtherImages = async () => {
      const imagePromises: Promise<void>[] = [];

      // 预加载所有其他AI的图片（在后台）
      aiChatData.forEach(character => {
        // 跳过当前AI的图片，因为已经单独处理
        if (character.id.toString() === id) return;

        // 预加载头像
        if (character.avatar) {
          imagePromises.push(preloadImage(character.avatar).catch(() => console.log(`Failed to preload: ${character.avatar}`)));
        }

        // 预加载主图片
        if (character.image) {
          imagePromises.push(preloadImage(character.image).catch(() => console.log(`Failed to preload: ${character.image}`)));
        }

        // 预加载图片集
        if (character.images && character.images.length > 0) {
          character.images.forEach(imgSrc => {
            imagePromises.push(preloadImage(imgSrc).catch(() => console.log(`Failed to preload: ${imgSrc}`)));
          });
        }
      });

      // 不阻塞UI，在后台加载
      Promise.allSettled(imagePromises).then(results => {
        console.log(`后台预加载完成: ${results.filter(r => r.status === 'fulfilled').length}/${imagePromises.length} 图片加载成功`);

        // 更新预加载状态
        const imageMap: Record<string, boolean> = {};
        aiChatData.forEach(character => {
          if (character.images && character.images.length > 0) {
            character.images.forEach(img => {
              imageMap[img] = true;
            });
          }
        });
        setPreloadedImages(imageMap);
      });
    };

    preloadOtherImages();
  }, [id]);

  // 监听背景图片变化
  useEffect(() => {
    if (id) {
      // 当页面重新获得焦点时检查背景图片是否变化
      const handleFocus = () => {
        const savedBgImage = localStorage.getItem(`bg_image_${id}`);
        if (savedBgImage && savedBgImage !== backgroundImage) {
          console.log('检测到背景图片变化，更新背景');
          setBackgroundImage(savedBgImage);
          setBackgroundLoaded(false); // 重置加载状态

          // 加载新背景
          const bgImg = new Image();
          bgImg.src = savedBgImage;
          bgImg.onload = () => {
            setBackgroundLoaded(true);
          };
        }
      };

      // 立即检查一次背景图片
      handleFocus();

      window.addEventListener('focus', handleFocus);

      // 页面可见性变化时也检查
      const handleVisibilityChange = () => {
        if (document.visibilityState === 'visible') {
          handleFocus();
        }
      };

      document.addEventListener('visibilitychange', handleVisibilityChange);

      return () => {
        window.removeEventListener('focus', handleFocus);
        document.removeEventListener('visibilitychange', handleVisibilityChange);
      };
    }
  }, [id, backgroundImage]);

  // 发起请求获取ai人设的信息 
  useEffect(() => {
    const getAiPersonInfo = async () => {
      const response = await request.get(`/api/ai-persons/getPersonInformation`, {
        params: {
          id: id
        }
      })
      if (response.status === 200) {
        console.log('ai人设信息', response.data.data)

        // 获取到AI人设信息后，确保头像和背景已设置
        const aiPersonData = response.data.data;
        if (aiPersonData && aiPersonData.image && !backgroundLoaded) {
          console.log('从API获取到背景图，立即设置', aiPersonData.avatar);
          setBackgroundImage(aiPersonData.image);
          setAiAvatar(aiPersonData.avatar)

          const bgImg = new Image();
          bgImg.src = aiPersonData.image;
          bgImg.onload = () => {
            setBackgroundLoaded(true);
          };
        }
      }
    }
    getAiPersonInfo()
  }, [id])

  // 保存聊天记录到localStorage
  const saveChatHistory = (msgs: Message[], sid: string) => {
    console.log('存储历史记录0', msgs, sid)
    if (id) {
      console.log('存储历史记录1')
      localStorage.setItem(`chat_history_${id}`, JSON.stringify(msgs))
      // 只有当sid存在且不为空时才保存
      if (sid) {
        console.log('存储历史记录2')
        const currentSavedSessionId = localStorage.getItem(`chat_session_${id}`);
        if (currentSavedSessionId !== sid) {
          console.log('存储历史记录3')
          localStorage.setItem(`chat_session_${id}`, sid)
        } else {
          console.log('保持当前会话ID:', sid);
        }
      } else {
        console.log('未提供会话ID，不更新会话ID存储');
      }
    }
  }

  // 从localStorage加载聊天记录
  const loadChatHistory = (): { messages: Message[], sessionId: string } => {
    if (!id) return { messages: [], sessionId: '' }

    const historyJson = localStorage.getItem(`chat_history_${id}`)
    console.log('获取记录1')
    console.log('historyJson', 'chat_history_${id}', JSON.parse(historyJson || '[]'))
    const sid = localStorage.getItem(`chat_session_${id}`) || ''
    console.log('获取记录2:', sid)
    if (historyJson) {
      try {
        const parsedHistory = JSON.parse(historyJson)
        // 确保日期对象正确解析
        const messages = parsedHistory.map((msg: any) => ({
          ...msg,
          timestamp: new Date(msg.timestamp)
        }))
        return { messages, sessionId: sid }
      } catch (e) {
        console.error('解析聊天记录失败:', e)
      }
    }

    return { messages: [], sessionId: '' }
  }

  // 清空聊天记录
  const clearChatHistory = () => {
    if (id) {
      console.log('删除记录1')
      localStorage.removeItem(`chat_history_${id}`)
      localStorage.removeItem(`chat_session_${id}`)
      setMessages([])
      setSessionId('')
      setShowConfirmDialog(false)
      setShowActions(false)
      // 确保重置loading状态
      setLoading(false)

      // 延迟展示欢迎消息
      setTimeout(() => {
        simulateWelcomeMessage()
      }, 1000)
    }
  }

  // 模拟流式展示欢迎消息
  const simulateWelcomeMessage = () => {
    const welcomeText = "Hello, what are you doing?"
    let index = 0

    // 清空当前响应
    setCurrentResponse('')

    // 确保重置loading状态
    setLoading(false)

    // 模拟打字效果
    const typingInterval = setInterval(() => {
      if (index < welcomeText.length) {
        setCurrentResponse(prev => prev + welcomeText.charAt(index))
        index++
      } else {
        clearInterval(typingInterval)

        // 完成"打字"后，添加到消息列表
        const welcomeMessage: Message = {
          id: `welcome_${Date.now()}`,
          content: welcomeText,
          sender: 'ai',
          timestamp: new Date(),
          emotionAnalysis: { joy: 0.8, neutral: 0.2 }
        }

        // 更新状态和引用
        setMessages([welcomeMessage])
        messagesRef.current = [welcomeMessage];
        setCurrentResponse('')

        // 再次确保loading状态重置
        setLoading(false)

        // 保存到localStorage
        console.log('保存历史记录')
        console.log('调用了 saveChatHistory 1')
        saveChatHistory([welcomeMessage], '')
      }
    }, 50) // 每50毫秒添加一个字符
  }

  // 初始化聊天会话
  useEffect(() => {
    const initChat = async () => {
      try {
        // 先检查访客认证
        const isAuthenticated = visitorAPI.checkAuth()

        if (!isAuthenticated) {
          console.log('访客未认证或认证已过期，重定向到首页')
          navigate('/')
          return
        }

        // 继续初始化过程 - 从localStorage加载历史记录
        const { messages: savedMessages, sessionId: savedSessionId } = loadChatHistory()

        if (savedMessages.length > 0) {
          // 如果有本地记录，直接使用并同步更新messagesRef
          setMessages(savedMessages)
          messagesRef.current = savedMessages;
          console.log('加载历史聊天记录:', savedMessages.length, '条消息');
          // console.log('历史消息内容:', savedMessages.map(m => `${m.sender}: ${m.content.substring(0, 20)}${m.content.length > 20 ? '...' : ''}`));

          if (savedSessionId) {
            setSessionId(savedSessionId)
          }
        } else {
          // 没有历史记录，延迟1.5秒后展示欢迎消息
          setTimeout(() => {
            simulateWelcomeMessage()
          }, 1500)
        }

        // 标记初始加载完成
        setTimeout(() => {
          setInitialLoadComplete(true);
          console.log('初始加载完成，后续音频将自动播放');
        }, 1000);
      } catch (error) {
        console.error('初始化聊天失败:', error)
        setInitialLoadComplete(true); // 确保出错时也会设置为完成
      }
    }

    initChat()
  }, [id, navigate])

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'auto' })
  }, [messages, currentResponse])

  // 清理音频资源
  useEffect(() => {
    return () => {
      if (currentAudio) {
        currentAudio.pause();
      }
      if (lastAudioUrl) {
        URL.revokeObjectURL(lastAudioUrl);
      }
      // 确保组件卸载时重置body的overflow样式
      document.body.style.removeProperty('overflow');
    };
  }, []);

  // 播放十六进制格式的音频数据
  const playAudioFromHex = (hexData: string, messageId: string) => {
    try {
      if (!hexData) {
        console.error("音频数据为空");
        return;
      }

      // 验证十六进制字符串
      if (!/^[0-9A-Fa-f]+$/.test(hexData)) {
        console.error("无效的十六进制数据");
        return;
      }

      // 如果当前正在播放该消息，或者该消息处于加载状态，则不再重复播放
      if (playingMessageId === messageId && (audioStatus === 'playing' || audioStatus === 'loading')) {
        console.log("该音频消息已在播放中或正在加载，不重复播放:", messageId);
        return;
      }

      setAudioStatus('loading');
      // 设置当前播放的消息ID
      setPlayingMessageId(messageId);
      // 重置播放进度
      setAudioProgress(0);

      // 如果有正在播放的音频，先停止
      if (currentAudio) {
        currentAudio.pause();
        setCurrentAudio(null);
      }

      // 如果有上一个音频URL，释放它
      if (lastAudioUrl) {
        URL.revokeObjectURL(lastAudioUrl);
        setLastAudioUrl(null);
      }

      // 将 hex 字符串转换为 Uint8Array
      const bytes = new Uint8Array(hexData.length / 2);
      for (let i = 0; i < hexData.length; i += 2) {
        try {
          const byteValue = parseInt(hexData.substring(i, i + 2), 16);
          if (isNaN(byteValue)) {
            console.error(`在位置 ${i} 处的值无效: ${hexData.substring(i, i + 2)}`);
            continue;
          }
          bytes[i / 2] = byteValue;
        } catch (e) {
          console.error(`处理位置 ${i} 的数据时出错:`, e);
        }
      }

      // 创建 Blob 并存储音频URL
      const blob = new Blob([bytes], { type: "audio/mp3" });
      const url = URL.createObjectURL(blob);
      setLastAudioUrl(url);

      // 创建音频元素并播放
      const audio = new Audio(url);

      // 添加加载事件处理
      audio.onloadeddata = function () {
        // 保存音频时长
        const duration = audio.duration;
        setAudioDurations(prev => ({
          ...prev,
          [messageId]: duration
        }));
      };

      // 添加时间更新处理
      audio.ontimeupdate = function () {
        if (audio.duration > 0) {
          setAudioProgress(audio.currentTime / audio.duration);
        }
      };

      setCurrentAudio(audio);

      audio.play()
        .then(() => {
          setAudioStatus('playing');
        })
        .catch(error => {
          console.error("音频播放失败:", error);
          setAudioStatus('idle');
          setPlayingMessageId(null);
          setAudioProgress(0);
        });

      // 播放完成后释放资源
      audio.onended = function () {
        setCurrentAudio(null);
        setAudioStatus('idle');
        setPlayingMessageId(null);
        setAudioProgress(0);
      };

      audio.onerror = function (e) {
        console.error("音频播放错误:", e);
        setCurrentAudio(null);
        setAudioStatus('idle');
        setPlayingMessageId(null);
        setAudioProgress(0);
      };
    } catch (error) {
      console.error("处理音频数据时出错:", error);
      setAudioStatus('idle');
      setPlayingMessageId(null);
      setAudioProgress(0);
    }
  };

  // 判断内容是否为音频十六进制数据
  const isAudioContent = (content: string): boolean => {
    // 如果内容为空或不是字符串，则不是音频内容
    if (!content || typeof content !== 'string') {
      return false;
    }

    // 检查是否是十六进制字符串
    const isHexString = /^[0-9A-Fa-f]+$/.test(content);

    // 如果是很长的十六进制字符串，则可能是音频数据
    // 音频数据通常较长，设置一个合理的最小长度阈值
    return isHexString && content.length > 1000;
  };

  // 处理语音模式数据 - 完全按照demo的处理方式，增加容错处理
  const handleVoiceModeData = (line: string): { audioData?: string, emotionAnalysis?: any, session_id?: string } => {
    // console.log('语音模式数据:', line);
    let result = {};

    try {
      // 去掉data:前缀
      const data = line.slice(6);
      // console.log('语音模式原始数据长度:', data.length);

      // 检查是否是合法的JSON格式（开始和结束）
      if (!data.trim().startsWith('{') || !data.trim().endsWith('}')) {
        console.log('数据不是完整的JSON格式，可能是分块数据');
        return result;
      }

      // 尝试提取音频数据，即使JSON解析失败
      if (data.includes("data") && data.includes("audio")) {
        console.log("当前数据块包含audio信息");

        try {
          // 尝试标准JSON解析
          const jsonData = JSON.parse(data);
          console.log("JSON解析成功");

          // 确保audio数据存在
          if (jsonData.audio && jsonData.audio.data && jsonData.audio.data.audio) {
            const audioHex = jsonData.audio.data.audio;
            console.log("提取到的audio十六进制值长度:", audioHex.length);

            result = {
              audioData: audioHex,
              emotionAnalysis: jsonData.emotion_analysis,
              session_id: jsonData.session_id
            };

            // 不再在这里设置加载状态，避免干扰自动播放逻辑
            // setAudioStatus('loading');
          }
        } catch (error) {
          console.error("标准JSON解析失败:", error);
          console.error("尝试使用正则表达式提取音频数据");

          // 使用正则表达式尝试提取音频数据
          try {
            // 尝试提取audio.data.audio字段
            const audioMatch = /"audio":\s*{\s*"data":\s*{\s*"audio":\s*"([^"]+)"/g.exec(data);
            if (audioMatch && audioMatch[1]) {
              const audioHex = audioMatch[1];
              console.log("通过正则提取的audio十六进制值长度:", audioHex.length);

              result = {
                audioData: audioHex
              };

              // 不再在这里设置加载状态，避免干扰自动播放逻辑
              // setAudioStatus('loading');
            }
          } catch (regexError) {
            console.error("正则提取失败:", regexError);
          }
        }
      }
      else if (data.includes("done") && data.includes("true")) {
        // 处理完成信号
        try {
          const jsonData = JSON.parse(data);
          result = {
            emotionAnalysis: jsonData.emotion_analysis,
            session_id: jsonData.session_id
          };

          // 更新会话ID（如果服务器返回了新的）
          if (jsonData.session_id && jsonData.session_id !== sessionId) {
            setSessionId(jsonData.session_id);
            console.log('更新session_id:', jsonData.session_id);
          }
        } catch (error) {
          console.error("解析done信号失败:", error);
        }
      }
    } catch (error) {
      console.error('解析语音数据失败:', error);
    }

    return result;
  };

  // 处理文本模式请求函数
  const handleTextSendMessage = async () => {
    if (!inputMessage.trim() || loading) return

    setLoading(true)
    setCurrentResponse('')

    try {
      const newMessage: Message = {
        id: Date.now().toString(),
        content: inputMessage,
        sender: 'user',
        timestamp: new Date(),
      }

      const updatedMessages = [...messages, newMessage]
      setMessages(updatedMessages)
      saveChatHistory(updatedMessages, sessionId)
      setInputMessage('')

      // 调用API发送消息（使用流式响应）
      const response = await chatAPI.sendMessage({
        sessionId,
        messages: [{
          role: 'user',
          content: inputMessage
        }],
        stream: true,
        chatId: id
      }, (chunk: string) => {
        // 确保chunk是有效字符串
        if (chunk) {
          setCurrentResponse(prev => prev + chunk);
          console.log('实时接收文本块:', chunk);
        }
      })

      // 打印机器人返回的完整数据
      console.log('AI响应数据:', response)

      // 添加AI回复
      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: response.response,
        sender: 'ai',
        timestamp: new Date(),
        emotionAnalysis: response.emotion_analysis
      }

      const finalMessages = [...updatedMessages, aiMessage]
      setMessages(finalMessages)
      setCurrentResponse('')

      // 保存到localStorage
      saveChatHistory(finalMessages, response.session_id)

      // 更新会话ID（如果变化）
      if (response.session_id !== sessionId) {
        setSessionId(response.session_id)
      }
    }
    catch (error) {
      console.error('发送消息失败2:', error)

      // 显示错误消息
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: '抱歉，我暂时无法回复。请稍后再试。',
        sender: 'ai',
        timestamp: new Date()
      }

      const updatedMessages = [...messages, errorMessage]
      setMessages(updatedMessages)
      saveChatHistory(updatedMessages, sessionId)
    } finally {
      setLoading(false)
    }
  };

  // 处理语音模式请求函数
  const handleVoiceSendMessage = async () => {
    console.log('handleVoiceSendMessage', '发送了语音消息')
    if (!inputMessage.trim() || loading) {
      return;
    }

    setLoading(true);

    try {
      // 获取访客token
      const visitorToken = localStorage.getItem('visitor_token') || '';

      // 创建新消息但先不更新UI
      const newMessage: Message = {
        id: Date.now().toString(),
        content: inputMessage,
        sender: 'user' as const,
        timestamp: new Date(),
      }

      // 先把输入框清空
      const messageToSend = inputMessage;
      setInputMessage('');

      // 准备API请求数据，使用当前messages加上新消息
      const requestMessages = [...messages, newMessage];

      console.log('语音模式: 只发送当前消息，而非历史记录', messageToSend);

      // 准备请求参数 - 只发送当前输入的消息，而不是整个历史记录
      const requestData: {
        messages: Array<{ role: string; content: string }>;
        stream: boolean;
        generate_voice: boolean;
        session_id?: string;
        chatId?: any
      } = {
        messages: [{
          role: 'user',
          content: messageToSend
        }],
        stream: true,
        generate_voice: true,// 语音模式
        chatId: id
      };

      // 仅在这时更新UI，添加用户消息
      setMessages(requestMessages);
      messagesRef.current = requestMessages;

      // 只有在会话ID可用时才添加
      if (sessionId) {
        requestData.session_id = sessionId;
      }

      // 这时才清除当前响应，避免清除已有AI消息
      setCurrentResponse('');

      // 直接使用fetch发送请求，完全按照demo处理方式
      const response = await fetch(`${API_BASE_URL}/chat/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': '*/*',
          'Authorization': `Bearer ${visitorToken}`
        },
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        throw new Error(`HTTP错误: ${response.status}`);
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let finalResponse: any = null;
      let audioData: string | null = null;

      // 用于累积可能分块的数据
      let accumulatedData = '';

      if (!reader) {
        throw new Error('无法获取响应读取器');
      }

      // 处理流式数据
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);

        // 处理分块情况，先累积数据
        accumulatedData += chunk;

        // 尝试找出完整的data块
        const lines = accumulatedData.split('\n');
        // 保留最后一个可能不完整的行
        accumulatedData = lines.pop() || '';

        for (const line of lines) {
          if (line.trim() === '') continue;

          if (line.startsWith('data: ')) {
            // 语音模式处理
            const result = handleVoiceModeData(line);

            if (result.audioData) {
              audioData = result.audioData;
              finalResponse = {
                response: '', // Language voice mode doesn't need text response
                emotion_analysis: result.emotionAnalysis || {},
                history: [],
                session_id: result.session_id || sessionId,
                audio: {
                  data: {
                    audio: audioData
                  }
                }
              };

              // Add audio message to interface immediately
              const audioMessage: Message = {
                id: (Date.now() + 2).toString(),
                content: audioData,
                sender: 'ai' as const,
                timestamp: new Date(),
                isAudio: true,
                emotionAnalysis: result.emotionAnalysis
              };

              // Update UI - use current latest message array
              setAudioResponseData(finalResponse);
              const newMessages = [...requestMessages, audioMessage];
              setMessages(newMessages);
              messagesRef.current = newMessages;

              // Save chat history with session_id from finalResponse
              const responseSessionId = result.session_id || sessionId;
              if (responseSessionId) {
                setSessionId(responseSessionId); // Ensure state update
                saveChatHistory(newMessages, responseSessionId);
                console.log('调用了 saveChatHistory 5')
              } else {
                saveChatHistory(newMessages, sessionId);
                console.log('调用了 saveChatHistory 6')
              }
              // 清除任何正在显示的响应
              setCurrentResponse('');
              // 在语音模式下收到音频数据后重置loading状态
              setLoading(false);
              // 结束流式处理，我们已经有了所需的数据
              break;
            } else if (!finalResponse) {
              // 如果收到了完成信号但还没有最终响应
              finalResponse = {
                response: '',
                emotion_analysis: result.emotionAnalysis || {},
                history: [],
                session_id: result.session_id || sessionId
              };

              // 更新会话ID（如果服务器返回了新的）
              if (result.session_id && result.session_id !== sessionId) {
                setSessionId(result.session_id);
                console.log('更新session_id (语音模式):', result.session_id);
              }
            }
          }
        }

        // 如果已经找到音频数据，提前结束循环
        if (audioData) {
          break;
        }
      }

      // 确保流式处理完成后重置loading状态（如果尚未重置）
      if (loading) {
        setLoading(false);
      }
    } catch (error) {
      console.error('发送语音消息失败:', error);
      setLoading(false);
    }
  };

  // 原来的handleSendMessage保留为兼容性函数，根据模式调用对应的处理函数
  const handleSendMessage = async () => {
    if (generateVoice) {
      await handleVoiceSendMessage();
    } else {
      await handleTextSendMessage();
    }
  };

  // 获取情感色彩
  const getEmotionColor = (message: Message) => {
    if (message.sender !== 'ai' || !message.emotionAnalysis) return ''

    // 找出最强的情感
    const emotions = message.emotionAnalysis
    console
    // Check if emotions is empty or invalid
    if (!emotions || Object.keys(emotions).length === 0) {
      return '#1e1e1e'; // Default color if no emotions data
    }

    // Add error handling for reduce operation
    try {
      const entries = Object.entries(emotions);
      if (entries.length === 0) {
        return '#1e1e1e';
      }

      const dominantEmotion = entries.reduce((a, b) =>
        a[1] > b[1] ? a : b
      )[0];

      const intensity = emotions[dominantEmotion] || 0.5

      // 根据情感类型返回不同的颜色
      const baseColors: Record<string, string> = {
        joy: 'rgb(255, 215, 0)', // 金色
        sadness: 'rgb(70, 130, 180)', // 钢蓝色
        anger: 'rgb(220, 20, 60)', // 猩红色
        fear: 'rgb(148, 0, 211)', // 紫色
        surprise: 'rgb(65, 105, 225)', // 皇家蓝
        love: 'rgb(107, 142, 35)', // 橄榄绿
        neutral: 'rgb(128, 128, 128)' // 灰色
      }

      const color = baseColors[dominantEmotion] || baseColors.neutral

      // 使用透明度表示情感强度
      return color.replace('rgb', 'rgba').replace(')', `, ${intensity * 0.5})`)
    } catch (error) {
      console.error('Error in getEmotionColor:', error);
      return '#1e1e1e'; // Default color on error
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  // 格式化音频时长
  const formatDuration = (seconds: number) => {
    if (isNaN(seconds)) return "00:00";
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 添加预加载音频时长的函数
  const preloadAudioDuration = (hexData: string, messageId: string) => {
    if (!hexData || typeof hexData !== 'string' || !/^[0-9A-Fa-f]+$/.test(hexData)) {
      return;
    }

    // 避免重复加载
    if (audioDurations[messageId] > 0) {
      return;
    }

    try {
      // 将 hex 字符串转换为 Uint8Array
      const bytes = new Uint8Array(hexData.length / 2);
      for (let i = 0; i < hexData.length; i += 2) {
        const byteValue = parseInt(hexData.substring(i, i + 2), 16);
        if (!isNaN(byteValue)) {
          bytes[i / 2] = byteValue;
        }
      }

      // 创建 Blob 并创建临时 Audio 对象
      const blob = new Blob([bytes], { type: "audio/mp3" });
      const url = URL.createObjectURL(blob);
      const audio = new Audio(url);

      // 监听加载完成事件以获取时长
      audio.addEventListener('loadedmetadata', () => {
        if (audio.duration && !isNaN(audio.duration)) {
          setAudioDurations(prev => ({
            ...prev,
            [messageId]: audio.duration
          }));
        }
        // 释放资源
        URL.revokeObjectURL(url);
      });

      // 设置加载事件，但不播放
      audio.load();
    } catch (error) {
      console.error("预加载音频时长失败:", error);
    }
  };

  // 在消息数据变化时预加载所有音频时长
  useEffect(() => {
    messages.forEach(message => {
      if (message.isAudio === true || isAudioContent(message.content)) {
        preloadAudioDuration(message.content, message.id);
      }
    });
  }, [messages]);

  // 添加自动播放最新音频消息功能
  useEffect(() => {
    // 确保有消息存在且初始加载已完成
    if (messages.length === 0 || !initialLoadComplete) return;

    // 获取最新的消息
    const latestMessage = messages[messages.length - 1];
    const latestMessageId = latestMessage.id;

    // 检查是否是AI发送的音频消息且未被播放过
    if (
      latestMessage.sender === 'ai' &&
      (latestMessage.isAudio || isAudioContent(latestMessage.content)) &&
      !autoPlayedMessagesRef.current.has(latestMessageId) &&
      audioStatus === 'idle' &&  // 确保当前没有正在播放的音频
      playingMessageId === null
    ) {
      console.log('尝试自动播放AI音频消息:', latestMessageId);

      // 标记为已处理，防止重复播放
      autoPlayedMessagesRef.current.add(latestMessageId);

      // 延迟一小段时间再播放，避免状态竞争
      const timeoutId = setTimeout(() => {
        // 再次检查状态和消息ID是否被标记，确保播放条件仍然满足
        if (
          audioStatus === 'idle' &&
          playingMessageId === null &&
          autoPlayedMessagesRef.current.has(latestMessageId)
        ) {
          console.log('开始自动播放最新的AI语音消息:', latestMessageId);
          playAudioFromHex(latestMessage.content, latestMessageId);
        } else {
          console.log('状态已改变，跳过自动播放');
        }
      }, 300);  // 增加延迟确保状态已稳定

      // 清理函数，防止组件卸载时仍然执行
      return () => clearTimeout(timeoutId);
    }
  }, [messages, initialLoadComplete, audioStatus, playingMessageId, isAudioContent, playAudioFromHex]); // 添加需要的依赖

  // 添加波形动画效果 - 使用RAF而不更新状态
  useEffect(() => {
    let frameId: number;
    const waveformElements = document.querySelectorAll('.audio-waveform-bar');

    // 只有在有正在播放的音频时才运行动画
    if (playingMessageId && audioStatus === 'playing' && waveformElements.length > 0) {
      const animate = () => {
        animationRef.current += 1;

        // 直接操作DOM元素，避免React重渲染
        waveformElements.forEach((el: Element, _index) => {
          const element = el as HTMLElement;
          if (element.dataset.messageId === playingMessageId) {
            const baseHeight = parseInt(element.dataset.baseHeight || "40");
            const position = parseInt(element.dataset.position || "0");

            // 使用余弦函数创造平滑的波浪效果
            const animFactor = 0.25 + (Math.cos((animationRef.current / 7) + position * 0.7) + 1) * 0.2;
            const newHeight = baseHeight * (0.9 + animFactor);

            element.style.height = `${newHeight}%`;
          }
        });

        frameId = requestAnimationFrame(animate);
      };

      frameId = requestAnimationFrame(animate);
      return () => {
        cancelAnimationFrame(frameId);
        // 重置所有波形到原始高度
        waveformElements.forEach((el: Element) => {
          const element = el as HTMLElement;
          if (element.dataset.messageId === playingMessageId) {
            element.style.height = `${element.dataset.baseHeight}%`;
          }
        });
      };
    }
  }, [playingMessageId, audioStatus]);

  // 为每个消息生成唯一的波形模式
  const getWaveformPattern = (messageId: string, length: number = 27) => {
    // 如果这个消息已经有预生成的模式，则直接返回
    if (waveformPatternsRef.current[messageId]) {
      return waveformPatternsRef.current[messageId];
    }

    // 生成一个新的波形模式并存储
    const pattern: number[] = [];

    // 使用messageId作为随机种子，确保同一消息每次生成相同的波形
    const seed = messageId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
    const pseudoRandom = (index: number) => {
      const value = Math.sin(seed + index * 997) * 10000;
      return Math.abs(value - Math.floor(value));
    };

    // 生成波形高度模式
    for (let i = 0; i < length; i++) {
      let height;

      if (i < 4 || i > length - 5) {
        // 两端低
        height = 20 + Math.floor(pseudoRandom(i) * 20);
      } else if (i > 7 && i < length - 8) {
        // 中间高
        height = 60 + Math.floor(pseudoRandom(i) * 30);
      } else {
        // 渐变过渡区
        height = 30 + Math.floor(pseudoRandom(i) * 40);
      }

      pattern.push(height);
    }

    // 缓存这个模式
    waveformPatternsRef.current[messageId] = pattern;
    return pattern;
  };

  return (
    <div className="flex flex-col h-screen bg-[#121212] relative">
      {/* Add DNS prefetching */}
      <DNSPrefetch />

      {/* 添加预加载组件 */}
      <PreloadAvatar src={aiAvatarUrl} />

      {/* Background image with progressive loading */}
      {backgroundImage && (
        <div
          className={`fixed inset-0 z-0 opacity-95 transition-opacity duration-500 ${backgroundLoaded ? 'bg-cover' : 'bg-blur animate-pulse'}`}
          style={{
            backgroundImage: `url(${backgroundImage})`,
            backgroundSize: '100% 100%',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
            filter: backgroundLoaded ? 'none' : 'blur(10px)',
            transition: 'filter 0.5s ease-in-out'
          }}
        />
      )}

      {/* Placeholder for background while loading */}
      {backgroundImage && !backgroundLoaded && (
        <div className="fixed inset-0 z-0 animate-pulse bg-gradient-to-b from-gray-900 to-gray-800"></div>
      )}

      {/* Content layer - make sure all content is above background */}
      <div className="relative z-10 flex flex-col h-full w-full overflow-hidden">
        {/* 头部 */}
        <div className="sticky top-0 left-0 right-0 z-10 flex items-center justify-between px-4 py-3 bg-[#1e1e1e] bg-opacity-95 border-b border-gray-800">
          <div className="flex items-center">
            <Link to={`/`} className="text-gray-400">
              <i className="fas fa-arrow-left"></i>
            </Link>
            <div className="flex items-center ml-4">
              {/* 确保顶部导航栏使用相同的头像组件 */}
              {aiAvatarComponent || (
                <div className="avatar-container">
                  <div className=" rounded-full w-8 h-8 ">
                    <img src={aiAvatar} alt={aiData.name} />
                  </div>
                </div>
              )}
              <span className="ml-3 font-medium text-white">{aiData.name}</span>
            </div>
          </div>
          {/* 右侧更多按钮 */}
          <div className="flex items-center">

            <div
              onClick={() => setShowActions(!showActions)}
              className="text-gray-400 p-2 rounded-full"
            >
              <i className="fas fa-ellipsis-v"></i>
            </div>
          </div>
        </div>

        {/* 聊天部分 */}
        <div className="flex-1 overflow-y-auto overscroll-contain p-4 pb-40 md:pb-36 space-y-4 touch-auto" style={{ WebkitOverflowScrolling: 'touch' }}>
          {messages.map((message) => {
            const isAudio = message.isAudio === true || isAudioContent(message.content);

            return (
              <div
                key={message.id}
                className={`flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                {message.sender === 'ai' && (
                  <div className="avatar-container mr-2 avatar-border">
                    <img
                      src={aiAvatar}
                      alt={aiData.name}
                      className={`prevent-distort ${avatarLoaded ? 'loaded' : ''}`}
                      loading="eager"
                    />
                  </div>
                )}
                
                {isAudio ? (
                  // 全新设计的语音气泡UI - 更简洁优雅
                  <div
                    className={`max-w-[70%] rounded-xl px-4 py-2.5 ${message.sender === 'ai'
                      ? 'bg-[#2a2a3a] border border-gray-700'
                      : 'bg-[#ff375f]'
                      } text-white cursor-pointer hover:bg-opacity-90 transition-all`}
                    onClick={() => playAudioFromHex(message.content, message.id)}
                  >
                    {/* 语音内容区 */}
                    <div className="flex items-center gap-3">
                      {/* 简洁播放/暂停按钮 */}
                      <div className={`flex-shrink-0 w-9 h-9 ${playingMessageId === message.id
                        ? 'bg-blue-500'
                        : 'bg-[#444459]'
                        } rounded-full flex items-center justify-center`}
                      >
                        {playingMessageId === message.id && audioStatus === 'loading' ? (
                          <svg className="animate-spin w-4 h-4 text-white" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                          </svg>
                        ) : playingMessageId === message.id && audioStatus === 'playing' ? (
                          <svg className="w-4 h-4 text-white" viewBox="0 0 24 24" fill="currentColor">
                            <rect x="6" y="4" width="4" height="16" rx="1" />
                            <rect x="14" y="4" width="4" height="16" rx="1" />
                          </svg>
                        ) : (
                          <svg className="w-3.5 h-3.5 text-white" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M8 5v14l11-7z" />
                          </svg>
                        )}
                      </div>

                      {/* 简化波形图 - 使用预生成的稳定波形 */}
                      <div className="flex-1 flex items-center h-7 overflow-hidden gap-[2px]">
                        {getWaveformPattern(message.id).map((height, index) => {
                          const isPlaying = playingMessageId === message.id && audioStatus === 'playing';

                          return (
                            <div
                              key={index}
                              className={`audio-waveform-bar w-[2px] rounded-full ${isPlaying
                                ? 'bg-blue-300'
                                : message.sender === 'ai' ? 'bg-gray-400' : 'bg-[#ff94ac]'
                                }`}
                              style={{
                                height: `${height}%`,
                                opacity: isPlaying ? 1 : 0.7,
                                transition: 'background-color 0.3s ease'
                              }}
                              data-message-id={message.id}
                              data-position={index}
                              data-base-height={height}
                            />
                          );
                        })}
                      </div>

                      {/* 时长标签 */}
                      <div className="flex-shrink-0 text-xs font-medium text-gray-200">
                        {audioDurations[message.id]
                          ? formatDuration(audioDurations[message.id])
                          : "00:00"}
                      </div>
                    </div>

                    {/* 底部时间戳 */}
                    <div className="flex justify-end mt-1.5">
                      <p className="text-xs text-gray-300 opacity-70">
                        {new Date(message.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                      </p>
                    </div>
                  </div>
                ) : (
                  //文本消息
                  <div
                    className={`max-w-[70%] rounded-lg px-4 py-2 ${message.sender === 'user'
                      ? 'bg-[#ff375f] text-white'
                      : 'bg-[#1e1e1e] bg-opacity-95 text-white'
                      }`}
                    style={{
                      backgroundColor: message.sender === 'ai'
                        ? getEmotionColor(message) || '#1e1e1e'
                        : undefined
                    }}
                  >
                    <p>{message.content}</p>
                    <p className={`text-xs text-gray-200 mt-1 ${message.sender === 'user' ? 'text-right' : ''}`}>
                      {new Date(message.timestamp).toLocaleTimeString()}
                    </p>
                  </div>
                )}
              </div>
            );
          })}

          {currentResponse && (
            <div className="flex justify-start">
              {/* 使用同一个头像组件实例 */}
              {aiAvatarComponent}
              <div className="max-w-[70%] rounded-lg px-4 py-2 bg-[#1e1e1e] bg-opacity-95 text-white">
                <p>{currentResponse}</p>
              </div>
            </div>
          )}

          <div ref={messagesEndRef} />
        </div>

        {/* Input Area - Increase z-index to ensure it's on top */}
        <div className="fixed bottom-0 left-0 right-0 border-t border-gray-800 bg-[#1e1e1e] bg-opacity-95 safe-area-padding-bottom z-20">
          <div className="p-4">
            <div style={{ backgroundColor: "white" }} className="flex items-center bg-[#2a2a2a] rounded-full px-4 py-2">
              <label className="flex items-center mr-3 text-black cursor-pointer">
                <input
                  type="checkbox"
                  checked={generateVoice}
                  onChange={(e) => setGenerateVoice(e.target.checked)}
                  className="mr-2"
                />
                <span className="text-sm" style={{ color: "rgb(75,85,99)" }}>Voice</span>
              </label>
              <input
                type="text"
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="Enter a message..."
                className="flex-1 bg-transparent text-[rgb(75,85,99)] outline-none"
                disabled={loading}
                // 添加onFocus事件，确保输入框获得焦点时内容能够完全可见
                onFocus={() => {
                  // 短暂延迟，确保键盘已经弹出
                  setTimeout(() => {
                    messagesEndRef.current?.scrollIntoView({ behavior: 'auto' });
                  }, 300);
                }}
              />

              {/* 文本模式按钮 */}
              {!generateVoice && (
                <button
                  onClick={handleTextSendMessage}
                  disabled={loading || !inputMessage.trim()}
                  className={`ml-2 px-4 py-1 rounded-full ${loading || !inputMessage.trim()
                    ? 'bg-gray-600 cursor-not-allowed'
                    : 'bg-[#ff375f] hover:bg-[#ff4f75]'
                    } text-white transition-colors`}
                >
                  {loading ? (
                    <i className="fas fa-spinner fa-spin"></i>
                  ) : (
                    <i className="fas fa-paper-plane"></i>
                  )}
                </button>
              )}

              {/* 语音模式按钮 */}
              {generateVoice && (
                <button
                  onClick={handleVoiceSendMessage}
                  disabled={loading}
                  className={`ml-2 px-4 py-1 rounded-full ${loading
                    ? 'bg-gray-600 cursor-not-allowed'
                    : 'bg-[#4f9fff] hover:bg-[#75b1ff]'
                    } text-white transition-colors flex items-center justify-center min-w-[44px] h-[36px]`}
                >
                  {loading ? (
                    <i className="fas fa-spinner fa-spin"></i>
                  ) : (
                    <i className="fas fa-microphone"></i>
                  )}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 操作菜单 */}
      {showActions && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
          onClick={() => {
            setShowActions(false);
            // 如果菜单关闭时仍在加载，重置加载状态
            if (loading) {
              setLoading(false);
            }
          }}
        >
          <div
            className="bg-[#1e1e1e] rounded-xl p-5 max-w-sm w-[80%] border border-gray-800 shadow-lg"
            onClick={(e) => e.stopPropagation()}
          >
            {/* 删除按钮  */}
            <div
              style={{ border: "1px solid rgb(255,77,77)" }}
              onClick={() => setShowConfirmDialog(true)}
              className="w-full text-center py-3 px-4 hover:bg-[#2a2a2a] rounded-lg mb-2 flex items-center justify-center"
            >
              <i className="fas fa-trash-alt mr-2 text-[rgb(255,77,77)]"></i> Clear your chat history
            </div>

            {/* 跳转到相册的按钮  */}
            <div
              style={{ border: "1px solid orange" }}
              className="w-full text-center py-3 px-4 hover:bg-[#2a2a2a] rounded-lg mb-2 flex items-center justify-center"
              onClick={() => {
                setShowActions(false);
                if (id) {
                  // 检查访客认证
                  const isAuthenticated = visitorAPI.checkAuth()

                  if (!isAuthenticated) {
                    console.log('访客未认证或认证已过期，重定向到首页')
                    navigate('/')
                    return
                  }

                  // 使用 navigate 进行路由跳转
                  navigate(`/AIPhotoAlbum/${id}/album`);
                }
              }}
            >
              <i className="fas fa-images mr-2 text-orange-400"></i> View the album
            </div>


            {/* 取消操作  */}
            <div
              style={{ border: "1px solid white" }}
              onClick={() => {
                setShowActions(false);
                // 取消时也重置加载状态
                setLoading(false);
              }}
              className="w-full text-center py-3 px-4 hover:bg-[#2a2a2a] rounded-lg flex items-center justify-center"
            >
              <i className="fas fa-times mr-2"></i> Cancel
            </div>
          </div>
        </div>
      )}

      {/* 确认对话框 */}
      {showConfirmDialog && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
          onClick={() => {
            setShowConfirmDialog(false);
            // 如果对话框关闭时仍在加载，重置加载状态
            if (loading) {
              setLoading(false);
            }
          }}
        >
          <div
            className="bg-[#1e1e1e] rounded-lg p-5 max-w-sm w-full border border-gray-800 shadow-lg"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="text-xl text-white mb-4">Clear your chat history</h3>
            <p className="text-gray-300 mb-6">Are you sure you want to empty all chats with that digital person? This action cannot be undone.。</p>
            <div className="flex justify-end space-x-3">
              <button
                onClick={() => {
                  setShowConfirmDialog(false);
                  // 取消时也重置加载状态
                  setLoading(false);
                }}
                className="px-4 py-2 rounded-lg bg-gray-700 text-white hover:bg-gray-600"
              >
                Cancel
              </button>
              <button
                onClick={clearChatHistory}
                className="px-4 py-2 rounded-lg bg-[#ff375f] text-white hover:bg-[#ff4f75]"
              >
                Confirm the emptying
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  )
}

export default AIChat 